package cc.miwuya.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Slf4j
@Data
@Component
public class JwtUtils {

    private static final String secret = "miwusenlin_Community";
    private static final long expire = 3600000L;

    /**
     * 生成jwt token
     */
    public static String generateToken(long userId, String issuer, Map<String, Object> map) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setClaims(map)
                .setIssuedAt(nowDate)
                .setIssuer(issuer)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public static Claims getClaimByToken(String token, String issuer) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            System.out.println("owner" + issuer);
            System.out.println(claims.getIssuer());
            if (issuer == null || !claims.getIssuer().equals(issuer)) {
                return null;
            }
            return claims;
        } catch (Exception e) {
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
